<template>
  <div class="sys-section-bg">
    <div style="height:32px;"></div>
    <el-row :gutter="20" class="sys-stat-row">
      <el-col :span="8">
        <el-card shadow="hover" class="sys-stat-card">
          <div class="stat-card">
            <el-icon color="#409EFF" size="22"><i-ep-s-check /></el-icon>
            <div class="stat-info">
              <div class="stat-title">角色总数</div>
              <div class="stat-value">{{ roles.length }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="sys-stat-card">
          <div class="stat-card">
            <el-icon color="#67C23A" size="22"><i-ep-user /></el-icon>
            <div class="stat-info">
              <div class="stat-title">管理员数</div>
              <div class="stat-value">{{roles.filter(r => r.role.includes('管理员')).length}}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="sys-stat-card">
          <div class="stat-card">
            <el-icon color="#E6A23C" size="22"><i-ep-user /></el-icon>
            <div class="stat-info">
              <div class="stat-title">角色类型</div>
              <div class="stat-value">{{[...new Set(roles.map(r => r.role))].length}}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-divider content-position="left">角色列表</el-divider>
    <div class="page-title">
      <el-icon><i-ep-s-check /></el-icon>
      <span style="margin-left: 8px; font-size: 20px; font-weight: bold;">角色管理</span>
    </div>
    <div class="toolbar">
      <el-input v-model="roleSearch" placeholder="请输入角色名称/身份/描述" style="width: 240px; margin-right: 16px;" clearable />
      <el-button type="primary" @click="handleRoleSearch">搜索</el-button>
      <el-button type="success" @click="openAddRoleDialog" style="margin-left: 16px;">添加角色</el-button>
    </div>
    <el-table :data="pagedRoles" style="width: 100%;">
      <el-table-column prop="name" label="角色名称" />
      <el-table-column prop="role" label="角色身份" />
      <el-table-column prop="desc" label="描述" />
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button size="small" @click="openEditRoleDialog(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDeleteRole(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination background layout="total, prev, pager, next, jumper" :total="filteredRoles.length" :page-size="rolePageSize" :current-page="roleCurrentPage" @current-change="handleRolePageChange" style="margin-top: 16px; text-align: right;" />
    
    <el-dialog :title="roleDialogMode === 'add' ? '添加角色' : '编辑角色'" v-model="roleDialogVisible" width="500px" @close="resetRoleDialog">
      <el-form :model="roleDialogForm" :rules="roleDialogRules" ref="roleDialogFormRef" label-width="80px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleDialogForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model="roleDialogForm.desc" type="textarea" :rows="3" placeholder="请输入角色描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="roleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRoleDialog" :loading="roleSubmitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { getApiUrl } from '../config/api.js'

// 角色管理数据
const roles = ref([])

// 获取角色数据（对接后端）
async function fetchRoles() {
  try {
    const token = localStorage.getItem('token')
    const res = await axios.get(getApiUrl('/role/list'), {
      headers: { 'Authorization': `Bearer ${token}` }
    })
    if (res.data && Array.isArray(res.data)) {
      roles.value = res.data.map(role => ({
        id: role.id,
        name: role.name,
        role: role.name,
        desc: role.description || ''
      }))
    } else {
      roles.value = []
    }
    console.log('获取到的角色数据:', roles.value)
  } catch (e) {
    console.error('获取角色失败:', e)
    ElMessage.error('获取角色失败: ' + (e.response?.data || e.message))
    roles.value = []
  }
}

// 创建角色
async function createRole(roleData) {
  try {
    const token = localStorage.getItem('token')
    const res = await axios.post(getApiUrl('/role/create'), {
      name: roleData.name,
      description: roleData.desc,
      permissionIds: [] // Assuming permissionIds is not part of the dialog form for now
    }, {
      headers: { 'Authorization': `Bearer ${token}` }
    })
    
    if (res.data && res.data.success) {
      ElMessage.success('添加成功')
      return true
    }
  } catch (e) {
    console.error('创建角色失败:', e)
    ElMessage.error('创建角色失败: ' + (e.response?.data || e.message))
    return false
  }
}

// 更新角色
async function updateRole(roleData) {
  try {
    const token = localStorage.getItem('token')
    const res = await axios.put(getApiUrl(`/role/update/${roleData.id}`), {
      name: roleData.name,
      description: roleData.desc,
      permissionIds: [] // Assuming permissionIds is not part of the dialog form for now
    }, {
      headers: { 'Authorization': `Bearer ${token}` }
    })
    
    if (res.data && res.data.success) {
      ElMessage.success('编辑成功')
      return true
    }
  } catch (e) {
    console.error('更新角色失败:', e)
    ElMessage.error('更新角色失败: ' + (e.response?.data || e.message))
    return false
  }
}

// 删除角色
async function deleteRole(roleId) {
  try {
    const token = localStorage.getItem('token')
    const res = await axios.delete(getApiUrl(`/role/delete/${roleId}`), {
      headers: { 'Authorization': `Bearer ${token}` }
    })
    
    if (res.data && res.data.success) {
      ElMessage.success('删除成功')
      return true
    }
  } catch (e) {
    console.error('删除角色失败:', e)
    ElMessage.error('删除角色失败: ' + (e.response?.data || e.message))
    return false
  }
}

const roleSearch = ref('')
const roleSearchKeyword = ref('')
const rolePageSize = ref(10)
const roleCurrentPage = ref(1)
const roleDialogVisible = ref(false)
const roleDialogMode = ref('add')
const roleDialogForm = ref({ id: null, name: '', desc: '' })
const roleDialogFormRef = ref(null)
const roleSubmitLoading = ref(false)
const roleDialogRules = {
  name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  desc: [{ required: false, message: '请输入描述', trigger: 'blur' }]
}

const filteredRoles = computed(() => {
  if (!roleSearchKeyword.value) return roles.value
  return roles.value.filter(r =>
    r.name.includes(roleSearchKeyword.value) ||
    r.role.includes(roleSearchKeyword.value) ||
    r.desc.includes(roleSearchKeyword.value)
  )
})

const pagedRoles = computed(() => {
  const start = (roleCurrentPage.value - 1) * rolePageSize.value
  return filteredRoles.value.slice(start, start + rolePageSize.value)
})

function handleRoleSearch() {
  roleSearchKeyword.value = roleSearch.value
  roleCurrentPage.value = 1
}

function openAddRoleDialog() {
  roleDialogMode.value = 'add'
  Object.assign(roleDialogForm.value, { id: null, name: '', desc: '' })
  roleDialogVisible.value = true
  nextTick(() => roleDialogFormRef.value && roleDialogFormRef.value.clearValidate())
}

function openEditRoleDialog(row) {
  roleDialogMode.value = 'edit'
  Object.assign(roleDialogForm.value, { 
    id: row.id, 
    name: row.name, 
    desc: row.desc 
  })
  roleDialogVisible.value = true
  nextTick(() => roleDialogFormRef.value && roleDialogFormRef.value.clearValidate())
}

function resetRoleDialog() {
  Object.assign(roleDialogForm.value, { id: null, name: '', desc: '' })
}

async function submitRoleDialog() {
  roleDialogFormRef.value.validate(async valid => {
    if (!valid) return
    
    roleSubmitLoading.value = true
    try {
      let success = false
      
      if (roleDialogMode.value === 'add') {
        success = await createRole(roleDialogForm.value)
      } else {
        success = await updateRole(roleDialogForm.value)
      }
      
      if (success) {
        roleDialogVisible.value = false
        await fetchRoles()
      }
    } catch (error) {
      console.error('提交失败:', error)
    } finally {
      roleSubmitLoading.value = false
    }
  })
}

async function handleDeleteRole(row) {
  try {
    await ElMessageBox.confirm(`确定要删除角色 ${row.name} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const success = await deleteRole(row.id)
    if (success) {
      await fetchRoles()
      nextTick(() => {
        if (pagedRoles.value.length === 0 && roleCurrentPage.value > 1) {
          roleCurrentPage.value--
        }
      })
    }
  } catch (error) {
    console.log('用户取消删除')
  }
}

function handleRolePageChange(page) {
  roleCurrentPage.value = page
}

onMounted(() => {
  fetchRoles()
})
</script>

<style scoped>
/* 系统管理内容区美化 */
.sys-section-bg {
  background: linear-gradient(135deg, #f8fafc 0%, #e6ecf5 100%);
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 64, 255, 0.06);
  padding: 32px 32px 24px 32px;
  margin-bottom: 24px;
  min-height: 600px;
  max-width: 1400px;
  width: 92vw;
  margin-left: auto;
  margin-right: auto;
}

/* 统计行和卡片样式 */
.sys-stat-row {
  margin-bottom: 24px;
}

.sys-stat-card {
  margin-bottom: 16px;
}

.toolbar {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.page-title {
  display: flex;
  align-items: center;
  margin-bottom: 18px;
}

/* 统计卡片样式 */
.stat-card {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.stat-info {
  margin-left: 16px;
}

.stat-title {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin: 4px 0;
}
</style> 